import subprocess  
import threading  
import time  
import os
import signal
import socket

class Modbus_Server():
    def __init__(self):

        self.received_IP = None
        self.received_Port = None 
        self.data_lock = threading.Lock()  # 用于保护对 received_data 的访问 
        # 指定要执行的命令  
        command = ["gcc", "/home/teamhd/sdk/src/tcpmodbus_server.c", "-o", "/home/teamhd/sdk/src/tcpmodbus_server", "-pthread"]  
        
        try:  
            # 执行命令  
            result = subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)  
            print("Compilation successful:\n", result.stdout.decode())  
        except subprocess.CalledProcessError as e:  
            print("An error occurred during compilation:\n", e.stderr.decode())  

    def start_modbus_server(self):  
        # 启动C实现的Modbus服务器  
        server_process = subprocess.Popen(["/home/teamhd/sdk/src/tcpmodbus_server"])  
        print("Modbus TCP Server started")  
        return server_process  

    def keep_alive(self):  
        # 这个线程将保持运行，直到主程序被终止  
        while True:  
            try:  
                time.sleep(1)  
            except KeyboardInterrupt:  
                print("Received exit signal...")  
                if self.server:  
                    os.kill(self.server.pid, signal.SIGTERM)  
                    print("Modbus server terminated.")  
                break  

    def receive_client_address(self):  
        # 设定Unix域套接字路径  
        socket_path = '/tmp/modbus_socket'  

        # 创建Unix域套接字  
        server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)  
        
        # 确保之前的socket文件不存在  
        if os.path.exists(socket_path):  
            os.unlink(socket_path)  

        server.bind(socket_path)  
        server.listen(1)  

        print("Listening for client address information...")  
        
        while True:  
            conn, _ = server.accept()  
            try:  
                data = conn.recv(256)  
                if data:  
                    data = data.decode()
                    address, port = data.split(':') 
                    if address != "127.0.0.1":
                        self.received_IP = address
                        self.received_Port = port
                    # print(f"Received: {self.received_data}")   
            finally:  
                conn.close() 

    def run(self):  
        self.server = self.start_modbus_server()  
        # 启动监听客户端地址信息的线程  
        address_thread = threading.Thread(target=self.receive_client_address)  
        address_thread.start()  
        self.keep_alive()

if __name__ == "__main__":
    modbus_server_instance = Modbus_Server()  
    server_thread = threading.Thread(target=modbus_server_instance.run)  
    server_thread.start()  
    server_thread.join()  # 等待线程完成  